package com.avic.rong.auditcertification.fragment;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.avic.rong.BaseActivity;
import com.avic.rong.BuildConfig;
import com.avic.rong.R;
import com.avic.rong.api.UploadPhotoApi;
import com.avic.rong.auditcertification.api.RongAuthApi;
import com.avic.rong.auditcertification.bean.CertificationMsgBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.SDCardUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.HideKeyBroadUtils;
import com.avic.rong.wedgit.StringUtil;
import com.avic.rong.wedgit.customWedgit.SheetDialog;
import com.avic.rong.wedgit.permissionschecker.PermissionChecker;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.CircleProgressDialog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.orhanobut.logger.Logger;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.annotations.Nullable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

import static com.avic.rong.activity.product.OnlineCServiceActivity.recycleBitmap;
import static com.avic.rong.utils.Utils.getContext;


//专家信息
public class ExpertInfoActivity extends BaseActivity {



    private String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @BindView(R.id.bt_next)
    Button btNext;
    @BindView(R.id.img_resume)
    ImageView imgResume;
    @BindView(R.id.img_upadd)
    ImageView imgUpadd;
    @BindView(R.id.et_honor)
    EditText etHonor;
    @BindView(R.id.et_publications)
    EditText etPublications;
    @BindView(R.id.et_projectexperience)
    EditText etProjectexperience;
    @BindView(R.id.iv_del)
    ImageView ivDel;
    private CertificationMsgBean authBean = new CertificationMsgBean();
    private SheetDialog sheetDialog;
    private CircleProgressDialog circleProgressDialog;
    private PermissionChecker permissionChecker;
    private String cameraPath;
    private int TAKE_CAMERA_PHOTO = 200;
    private String imgUrl = "";


    @Override
    protected int getContentViewId() {
        return R.layout.activity_expert_info;
    }
    //15124690041
    @Override
    protected void initView() {
        tvTitle.setText("个人认证");

        circleProgressDialog = new CircleProgressDialog(context);
        permissionChecker = new PermissionChecker(this);
        if (getIntent()!=null){
            CertificationMsgBean data = (CertificationMsgBean) getIntent().getSerializableExtra("authbean");
            authBean = data;
            authBean.setUserName(data.getUserName());
            authBean.setMainFields(data.getMainFields());
            authBean.setUserDesc(data.getUserDesc());
            authBean.setIntroduction(data.getIntroduction());
            authBean.setLogo(data.getLogo());
            authBean.setHomePageLogo(data.getHomePageLogo());
            authBean.setRealName(data.getRealName());
            authBean.setCompany(data.getCompany());
            authBean.setPosition(data.getPosition());
            if (!StringUtil.isEmpty(data.getPersonalResume())) {
                Glide.with(context).applyDefaultRequestOptions(RequestOptions.fitCenterTransform()).load(data.getPersonalResume()).into(imgResume);
                imgUpadd.setVisibility(View.GONE);
                ivDel.setVisibility(View.VISIBLE);
            }
            etHonor.setText(data.getAchievementHonor());
            etProjectexperience.setText(data.getProjectExperience());
            etPublications.setText(data.getPublications());
        }


    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        HideKeyBroadUtils.hide(this,ev);
        return super.dispatchTouchEvent(ev);
    }


    @Override
    protected void addListener() {
        Map<String,String> map = new HashMap<>();
        btNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String honor = etHonor.getText().toString().trim();
                String projectExperience = etProjectexperience.getText().toString().trim();
                String publicxtion = etPublications.getText().toString().trim();
                map.put("logo",authBean.getLogo());
                map.put("userName",authBean.getUserName());
                map.put("mainFields",authBean.getMainFields());
                map.put("introduction",authBean.getIntroduction());
                map.put("userDesc",authBean.getUserDesc());
                if (authBean.getHomePageLogo() != null){
                    map.put("homePageLogo",authBean.getHomePageLogo());
                }
                map.put("realName",authBean.getRealName());
                map.put("position",authBean.getPosition());
                map.put("company",authBean.getCompany());
                if (!StringUtil.isEmpty(imgUrl)) {
                    map.put("personalResume", imgUrl);
                }
                map.put("achievementHonor",honor);
                map.put("publications",publicxtion);
                map.put("projectExperience",projectExperience);
                map.put("token", SharedPreferencesUtil.getLoginToken());

                RongAuthApi rongAuthApi = new RongAuthApi(ExpertInfoActivity.this,authHttpOnNextListener );
                rongAuthApi.setShowProgress(true);
                rongAuthApi.setCancel(false);
                rongAuthApi.setMap(map);
                HttpManager.getInstance().doHttpDeal(rongAuthApi);
            }
        });
    }

    HttpOnNextListener<BaseResultEntity> authHttpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                ToastTools.showPublicToast(baseResultEntity.getMsg());
                return;
            }
            startActivity(FinishWriteActivity.queryIntent(ExpertInfoActivity.this));
        }
    };



    public static Intent queryIntent(Context context, CertificationMsgBean bean) {
        Intent intent = new Intent(context, ExpertInfoActivity.class);
        intent.putExtra("authbean", bean);
        return intent;
    }

    @OnClick({R.id.img_upadd,R.id.img_resume,R.id.iv_del})
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.img_upadd:
                showFileChooser();
                break;
            case R.id.iv_del:
                imgUpadd.setVisibility(View.VISIBLE);
                ivDel.setVisibility(View.GONE);
                imgResume.setImageDrawable(null);
                break;
        }
    }

    private void showFileChooser(){
        sheetDialog =  new SheetDialog.Builder(this).setTitle(ConstantsUtils.EMPTY_STR)
                .addMenu("拍照", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            cameraPath = SDCardUtils.getSDCardPath() + "/temp.png";
                            File file = new File(cameraPath);
                            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(getContext(), BuildConfig.APPLICATION_ID + ".provider", file));
                            }else{
                                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                            }

                            intent.putExtra("return-data", false);
                            intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
                            intent.putExtra("noFaceDetection", true);
                            startActivityForResult(intent, TAKE_CAMERA_PHOTO);
                        }
                    }
                })
                .addMenu("从相册中选择", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        if (sheetDialog != null && sheetDialog.isShowing()){
                            sheetDialog.dismiss();
                        }
                        if (permissionChecker.isLackPermissions(PERMISSIONS)) {
                            permissionChecker.requestPermissions();
                        } else {
                            startPickPhoto();
                        }
                    }
                }).setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sheetDialog.dismiss();
                    }
                }).create();
        sheetDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
            }
        });
        sheetDialog.show();
    }

    private void startPickPhoto() {
        PictureSelector.create(this).openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                .maxSelectNum(1)
                .minSelectNum(1)// 最小选择数量
                .imageSpanCount(3)// 每行显示个数
                .selectionMode(PictureConfig.SINGLE)// 多选 or 单选
                .previewImage(true)// 是否可预览图片
                .isCamera(false)// 是否显示拍照按钮
                .isZoomAnim(false)// 图片列表点击 缩放效果 默认true
                .compress(true)// 是否压缩
                .enableCrop(true)
                .glideOverride(260, 260)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                .hideBottomControls(true)// 是否显示uCrop工具栏，默认不显示
                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
                .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
                .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
                .minimumCompressSize(100)// 小于100kb的图片不压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code`
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == TAKE_CAMERA_PHOTO){//拍照
                compressPictureUpload(cameraPath);
            }else if(requestCode == PictureConfig.CHOOSE_REQUEST){//选择照片

                // 图片选择结果回调
                // 例如 LocalMedia 里面返回三种path
                // 1.media.getPath(); 为原图path
                // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                List<LocalMedia> tempList = PictureSelector.obtainMultipleResult(data);
                for (LocalMedia media : tempList) {
                    if (media.isCompressed()&&media.isCut()) {
                        Logger.i("图片-----》", media.getCompressPath());
                        circleProgressDialog.show();
                        upLoad(media.getCompressPath());
                    }
                }
            }
            sheetDialog.cancel();
        }
    }

    //压缩并上传图片
    private Bitmap bitmap;
    private File uploadFile;
    private void compressPictureUpload(String imagePath){
        circleProgressDialog.show();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        bitmap = BitmapFactory.decodeFile(imagePath, options);

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                uploadFile = compressImage(bitmap);
                emitter.onNext(uploadFile.getAbsolutePath());
            }
        }).subscribeOn(Schedulers.computation()).observeOn(Schedulers.newThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String temp) throws Exception {
                upLoad(temp);
                recycleBitmap(bitmap);
            }
        });
    }

    /**
     * 压缩图片（质量压缩）
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 5 * 1024 && options > 10) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            Logger.i("-----------------------------option:" + options);
            if (options > 0) {//options 的范围为0--100
                bitmap.compress(Bitmap.CompressFormat.PNG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            }
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                Logger.e(e.getMessage());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            Logger.e(e.getMessage());
            e.printStackTrace();
        }
        recycleBitmap(bitmap);
        return file;
    }


    /*
     * 上传头像
     * */
    public void upLoad(String photoPath){
        UploadPhotoApi uploadPhotoApi = new UploadPhotoApi(this,httpOnNextListener );
        File file = new File(photoPath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"),file);
        MultipartBody.Part part =  MultipartBody.Part.createFormData("file",file.getName(),requestBody);
        uploadPhotoApi.setPart(part);
        HttpManager.getInstance().doHttpDeal(uploadPhotoApi);
    }

    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)){
                imgUrl = (String) baseResultEntity.getData();
                Log.e("ExpertInfoActivity", "onNext: "+imgUrl );
                RequestOptions apply = new RequestOptions().
                        error(R.mipmap.asd_stan)
                        .apply(RequestOptions.fitCenterTransform()).
                        placeholder(R.mipmap.ic_launcher)
                        .skipMemoryCache(true);
                Glide.with(ExpertInfoActivity.this).applyDefaultRequestOptions(apply)
                        .load(imgUrl)
                        .listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                circleProgressDialog.dismiss();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                imgResume.setImageDrawable(resource);
                                circleProgressDialog.dismiss();
                                ToastTools.showPublicToast("上传成功了");
                                imgUpadd.setVisibility(View.GONE);
                                ivDel.setVisibility(View.VISIBLE);
                                return false;
                            }
                        }).into(imgResume);
            }else {
                Toast.makeText(ExpertInfoActivity.this, baseResultEntity.getMsg(), Toast.LENGTH_SHORT).show();
            }
        }
    };


}
